package com.ctshk.rpc.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.IsRead;
import com.ctshk.common.enums.MessageType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.system.dto.SysMessageDTO;
import com.ctshk.rpc.system.dto.SysMessageTotalDTO;
import com.ctshk.rpc.system.entity.SystemMessage;
import com.ctshk.rpc.system.mapper.SystemMessageMapper;
import com.ctshk.rpc.system.req.SysMessageListIdReq;
import com.ctshk.rpc.system.req.SysMessageQueryReq;
import com.ctshk.rpc.system.req.SysMessageReq;
import com.ctshk.rpc.system.service.ISystemMessageService;
import org.apache.dubbo.config.annotation.DubboService;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * 系统消息表 服务实现类
 *
 *
 * @author 谢诗宏
 * @since 2020-12-28
 */
@DubboService
public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, SystemMessage> implements ISystemMessageService {

    @Override
    public Result add(SysMessageReq req, Long userId) {
        String str = MessageType.BACKLOG.getCode() == req.getType() ? "处理" : "查看";
        SystemMessage copy = EntityUtil.copy(req, SystemMessage.class);
        Long id = IdWorker.getId();
        copy.setId(id);
        copy.setIsDeleted(IsDeletedCode.NO.getCode());
        copy.setIsRead(IsRead.UNREAD.getCode());
        copy.setCreateId(userId);
        copy.setCentent("您有一条 (" + req.getTitle() + ")【" + req.getBusinessOrderNo() + "】,请及时" + str + "!");
        copy.setSendingTime(req.getSendingTime() == null ? LocalDateTime.now() : req.getSendingTime());
        copy.setGmtCreate(LocalDateTime.now());
        int insert = baseMapper.insert(copy);
        if (insert > 0) {
            return Result.success(id);
        }
        return Result.failed(SystemError.SYS_437);
    }

    @Override
    public Result addAll(List<SysMessageReq> reqs, Long userId) {
        List<SystemMessage> list = new ArrayList<>();
        for (SysMessageReq req:reqs) {
            String str = MessageType.BACKLOG.getCode() == req.getType() ? "处理" : "查看";
            SystemMessage copy = EntityUtil.copy(req, SystemMessage.class);
            copy.setId(IdWorker.getId());
            copy.setIsDeleted(IsDeletedCode.NO.getCode());
            copy.setIsRead(IsRead.UNREAD.getCode());
            copy.setCreateId(userId);
            copy.setCentent("您有一条 (" + req.getTitle() + ")【" + req.getBusinessOrderNo() + "】,请及时" + str + "!");
            copy.setSendingTime(req.getSendingTime() == null ? LocalDateTime.now() : req.getSendingTime());
            copy.setGmtCreate(LocalDateTime.now());
            list.add(copy);
        }
        if(list.size() > 0){
            super.saveBatch(list);
        }
        return Result.success();
    }

    @Override
    public Result read(SysMessageListIdReq req, Long usrId) {
        List<SystemMessage> systemMessageList = new ArrayList<>();
        SystemMessage systemMessage = null;
        for (Long id : req.getId()) {
            systemMessage = new SystemMessage();
            systemMessage.setId(id);
            systemMessage.setGmtModified(LocalDateTime.now());
            systemMessage.setModifiedId(usrId);
            systemMessage.setIsRead(IsRead.READ.getCode());
            systemMessageList.add(systemMessage);
        }
        boolean b = super.updateBatchById(systemMessageList);
        if (b) {
            return Result.success();
        }
        return Result.failed(SystemError.SYS_437);
    }

    @Override
    public Result read(Long id, Long usrId) {
        SystemMessage systemMessage = new SystemMessage();
        systemMessage.setId(id);
        systemMessage.setIsRead(IsRead.READ.getCode());
        systemMessage.setModifiedId(usrId);
        systemMessage.setGmtModified(LocalDateTime.now());
        int i = baseMapper.updateById(systemMessage);
        if (i > 0) {
            return Result.success();
        }
        return Result.failed(SystemError.SYS_437);
    }

    @Override
    public PageResponse<SysMessageDTO> queryList(SysMessageQueryReq sysMessageQueryReq, Long userId) {
        IPage<SystemMessage> page = new Page<>(sysMessageQueryReq.getPageNo(), sysMessageQueryReq.getPageSize());
        QueryWrapper<SystemMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SystemMessage::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(SystemMessage::getReceivingUserId, userId)
                .eq(null != sysMessageQueryReq.getBusinessType(), SystemMessage::getBusinessType, sysMessageQueryReq.getBusinessType())
                .like(null != sysMessageQueryReq.getSource(), SystemMessage::getSource, sysMessageQueryReq.getSource())
                .eq(null != sysMessageQueryReq.getType(), SystemMessage::getType, sysMessageQueryReq.getType())
                .eq(null != sysMessageQueryReq.getRead(), SystemMessage::getIsRead, sysMessageQueryReq.getRead())
                .gt(null != sysMessageQueryReq.getSendingTimeStart(), SystemMessage::getSendingTime, sysMessageQueryReq.getSendingTimeStart())
                .lt(null != sysMessageQueryReq.getSendingTimeEnd(), SystemMessage::getSendingTime, sysMessageQueryReq.getSendingTimeEnd())
                .orderByDesc(SystemMessage::getSendingTime);
        IPage<SystemMessage> iPage = baseMapper.selectPage(page, queryWrapper);
        List<SystemMessage> systemMessageList = iPage.getRecords();
        List<SysMessageDTO> sysMessageDTOList = EntityUtil.copyList(systemMessageList, SysMessageDTO.class);
        return new PageResponse<>(sysMessageDTOList, iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
    }

    @Override
    public Result delete(SysMessageListIdReq sysMessageListIdReq, Long userId) {
        List<SystemMessage> systemMessageList = new ArrayList<>();
        SystemMessage systemMessage = null;
        for (Long id : sysMessageListIdReq.getId()) {
            systemMessage = new SystemMessage();
            systemMessage.setId(id);
            systemMessage.setGmtModified(LocalDateTime.now());
            systemMessage.setIsDeleted(IsDeletedCode.YES.getCode());
            systemMessageList.add(systemMessage);
        }
        boolean b = super.updateBatchById(systemMessageList);
        if (b) {
            return Result.success();
        }
        return Result.failed(SystemError.SYS_437);
    }

    @Override
    public SysMessageTotalDTO getReadTotal(Long userId) {
        SysMessageTotalDTO sysMessageTotalDTO = new SysMessageTotalDTO();
        //待办条数
        QueryWrapper<SystemMessage> waitTotal = new QueryWrapper<SystemMessage>();
        waitTotal.lambda().eq(SystemMessage::getIsRead, IsRead.UNREAD.getCode())
                .eq(SystemMessage::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(SystemMessage::getType, MessageType.BACKLOG.getCode())
                .eq(SystemMessage::getReceivingUserId, userId);
        sysMessageTotalDTO.setWaitTotal(baseMapper.selectCount(waitTotal));
        //通知条数
        QueryWrapper<SystemMessage> noticeTotal = new QueryWrapper<SystemMessage>();
        noticeTotal.lambda().eq(SystemMessage::getIsRead, IsRead.UNREAD.getCode())
                .eq(SystemMessage::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(SystemMessage::getType, MessageType.INFORM.getCode())
                .eq(SystemMessage::getReceivingUserId, userId);
        sysMessageTotalDTO.setNoticeTotal(baseMapper.selectCount(noticeTotal));
        return sysMessageTotalDTO;
    }

    @Override
    public Result setAllRead(Long userId) {
        //将当前用户的未读的所有消息改为已读
        QueryWrapper<SystemMessage> queryWrapper = new QueryWrapper<SystemMessage>();
        queryWrapper.lambda().eq(SystemMessage::getReceivingUserId, userId)
                .eq(SystemMessage::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(SystemMessage::getIsRead, IsRead.UNREAD.getCode())
                .orderByDesc(SystemMessage::getSendingTime);
        SystemMessage systemMessage = new SystemMessage();
        systemMessage.setIsRead(IsRead.READ.getCode());
        systemMessage.setModifiedId(userId);
        systemMessage.setGmtModified(LocalDateTime.now());
        int update = baseMapper.update(systemMessage, queryWrapper);
        if (update > 0) {
            return Result.success();
        }
        return Result.failed(SystemError.SYS_437);
    }
}
